package com.baomidou.springwind.controller.supply;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.kisso.annotation.Permission;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.springwind.controller.BaseController;
import com.baomidou.springwind.controller.NodeData;
import com.baomidou.springwind.entity.NetworkSupply;
import com.baomidou.springwind.entity.Project;
import com.baomidou.springwind.entity.SysArea;
import com.baomidou.springwind.mapper.NetworkSupplyDao;
import com.baomidou.springwind.service.NetworkSupplyService;
import com.baomidou.springwind.service.ProjectService;
import com.baomidou.springwind.service.SysAreaService;
import com.baomidou.springwind.utils.ParamMap;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URLEncoder;
import java.util.*;

/**
 * <p>
 * 物流供应链
 * </p>
 *
 * @Author huangtao
 * @Date 2017-8-21
 */
@Controller
@RequestMapping("/network/supply")
public class NetworkSupplyController extends BaseController {

    @Autowired
    private NetworkSupplyService networkSupplyService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private SysAreaService sysAreaService;
    @Autowired
    private NetworkSupplyDao networkSupplyDao;

    /**
     * 供应链数据导入
     */
    @RequestMapping("/list")
    @Permission("1001")
    public String supplyList(Model model) {
        EntityWrapper<Project> wrapper = new EntityWrapper<Project>();
        wrapper.setSqlSelect("id,name");
        wrapper.eq("operator_id", getCurrentUserId());
        wrapper.in("state", Arrays.asList("1", "2"));
        model.addAttribute("prjList", projectService.selectList(wrapper));
        return pjaxPath("/file/network_supply_list", model);
    }

    /**
     * 客户分析主界面
     */
    @RequestMapping("/chain")
    @Permission("1001")
    public String customGroup(Model model) {
        EntityWrapper<NetworkSupply> wrapper = new EntityWrapper<NetworkSupply>();
        wrapper.eq("operator_id", getCurrentUserId());
        wrapper.eq("batch_id", getProjectId());
        wrapper.groupBy("branch_center");
        model.addAttribute("prjList", networkSupplyService.selectList(wrapper));
        return pjaxPath("/lpp/network/supply/main", model);
    }

    /**
     * 城市数据导入--客户分析数据--ajax获取数据
     */
    @ResponseBody
    @RequestMapping("/getData")
    @Permission("1001")
    public String getData(Page<NetworkSupply> page, String batchId) {
        page = new Page<NetworkSupply>(page.getCurrent(), page.getSize());
        EntityWrapper<NetworkSupply> wrapper = new EntityWrapper<NetworkSupply>();
        if (StringUtils.isEmpty(batchId)) {
            wrapper.eq("batch_id", getProjectId());
        }
        wrapper.eq("operator_id", getCurrentUserId());
        wrapper.orderBy("create_time", false);
        page = networkSupplyService.selectPage(page, wrapper);
        List<NetworkSupply> networkSupplyList = page.getRecords();
        if (networkSupplyList.size() > 0) {
            Project project = projectService.selectById(networkSupplyList.get(0).getBatchId());
            for (NetworkSupply networkSupply : networkSupplyList) {
                networkSupply.setBatchName(project == null ? "--" : project.getName());
            }
        }
        return jsonPage(page);
    }

    @ResponseBody
    @Permission("1001")
    @RequestMapping("/bar1")
    public String getMap(Long batchId, Model model) {
        JSONArray data = new JSONArray();
        Random random = new Random(47);
        //分组：一级配送中心
        EntityWrapper<NetworkSupply> wrapper1 = new EntityWrapper<NetworkSupply>();
        wrapper1.eq("batch_id", getProjectId());
        wrapper1.groupBy("branch_id");
        List<NetworkSupply> mapList1 = networkSupplyService.selectList(wrapper1);
        if(mapList1.size()==0){
            String message="查询数据异常";
            return callbackFail(message);
        }
        //分组：一级配送中心，二级配送中心
        EntityWrapper<NetworkSupply> wrapper2 = new EntityWrapper<NetworkSupply>();
        wrapper2.eq("batch_id", getProjectId());
        wrapper2.groupBy("branch_id");
        wrapper2.groupBy("delivery_id");
        List<NetworkSupply> mapList2 = networkSupplyService.selectList(wrapper2);

        String startnode = null;
        HashMap<String,List<NetworkSupply>> hashMap=new HashMap<String, List<NetworkSupply>>();
        for (int i=0;i<mapList1.size();i++){
            List<NetworkSupply> list=new ArrayList<NetworkSupply>();
            for (int j=0;j<mapList2.size();j++){
                if (mapList1.get(i).getBranchId().equals(mapList2.get(j).getBranchId())){
                    list.add(mapList2.get(j));
                }
            }
            hashMap.put(mapList1.get(i).getBranchCenter(),list);
        }
        for (Map.Entry<String,List<NetworkSupply>> map: hashMap.entrySet()) {
            JSONArray nodes = new JSONArray();
            JSONArray res = new JSONArray();
            JSONObject serie = new JSONObject();
            startnode = map.getKey();
            List<NetworkSupply> arrayList = map.getValue();
            for (int j = 0; j < arrayList.size(); j++) {
                nodes.add(new NodeData(startnode, Arrays.asList(arrayList.get(j).getDeliveryLng(), arrayList.get(j).getDeliveryLat(), random.nextInt(100))));
                JSONObject res1 = parseRes(arrayList.get(j));
                res.add(res1);
            }
            serie.put("name", startnode);
            serie.put("res", res);
            serie.put("nodes", nodes);
            data.add(serie);
        }
        return callbackSuccess(data);
    }

    private JSONArray loadlatlng(String placename) {
        JSONArray jsonArray = new JSONArray();
        EntityWrapper<SysArea> wrapper = new EntityWrapper<SysArea>();
        wrapper.eq("shortname", placename);
        wrapper.orderBy("level");
        List<SysArea> sysAreas = sysAreaService.selectList(wrapper);
        jsonArray.add(sysAreas.get(0).getLng());
        jsonArray.add(sysAreas.get(0).getLat());
        return jsonArray;
    }

    //通过地址名来获取到经纬度,调用百度地图来处理的
    private JSONArray latlng(String placename) {
        JSONArray jsonArray = new JSONArray();
        String url = String.format("http://api.map.baidu.com/geocoder?address=%s&output=json&key=%s", URLEncoder.encode(placename.toString()), "NURx5GUAQ1IBZVBMCQSpYppRsDdTpbxG");
        CloseableHttpClient client = HttpClients.createDefault();
        double lng = 0;
        double lat = 0;
        try {
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = client.execute(httpGet);

            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = httpResponse.getEntity();
                String text = EntityUtils.toString(httpEntity);//取出应答字符串
                JSONObject json = JSONObject.parseObject(text);
                lat = json.getJSONObject("result").getJSONObject("location").getDouble("lng");
                lng = json.getJSONObject("result").getJSONObject("location").getDouble("lat");
                jsonArray.add(lat);
                jsonArray.add(lng);
                System.out.println(placename + "--" + lat + "--" + lng);
                return jsonArray;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //对res进行处理
    private JSONObject parseRes(NetworkSupply networkSupply) {
        JSONObject res = new JSONObject();
        res.put("fromName", networkSupply.getBranchCenter());
        res.put("toName", networkSupply.getDeliveryCenter());
        JSONArray fromCoord = new JSONArray();
        fromCoord.add(networkSupply.getBranchLng());
        fromCoord.add(networkSupply.getBranchLat());
        JSONArray toCoord = new JSONArray();
        toCoord.add(networkSupply.getDeliveryLng());
        toCoord.add(networkSupply.getDeliveryLat());
        JSONArray coords = new JSONArray();
        coords.add(fromCoord);
        coords.add(toCoord);
        res.put("coords", coords);
        return res;
    }

    @ResponseBody
    @Permission("1001")
    @RequestMapping("/bar2")
    public String getBar2(Long batchId, Model model) {
        String center = request.getParameter("center");
        if (center.length() < 0 || center == "") {
            center = getId1();
        }
        EntityWrapper<NetworkSupply> wrapper = new EntityWrapper<NetworkSupply>();
        wrapper.eq("branch_id", center);
        wrapper.groupBy("order_type");
        wrapper.setSqlSelect("order_type type,sum(order_quantity) quantity,count(order_quantity) counts");
        wrapper.eq("batch_id", getProjectId());
        List<Map<String, Object>> mapList = networkSupplyService.selectMaps(wrapper);
        if(mapList.size()==0){
            String message="查询数据异常";
            return callbackFail(message);
        }
        JSONArray dataAxis = new JSONArray();
        JSONArray data = new JSONArray();
        JSONArray data2 = new JSONArray();
        JSONObject ret = new JSONObject();
        for (int i = 0; i < mapList.size(); i++) {
            dataAxis.add(mapList.get(i).get("type"));
            data.add(mapList.get(i).get("quantity"));
            data2.add(mapList.get(i).get("counts"));
        }
        ret.put("dataAxis", dataAxis);
        ret.put("y", data);
        ret.put("y2", data2);
        return callbackSuccess(ret);
    }
    public String getId1(){
        ParamMap<String,Object> pm=new ParamMap<String, Object>();
        pm.put("batchId",getProjectId());
        pm.put("operatorId",getCurrentUserId());
        List<Map<String, Object>> mapList = networkSupplyDao.selectBranch(pm);
        if(mapList!=null){
            return mapList.get(0).get("branchId").toString();
        }
        return null;
    }

    @ResponseBody
    @Permission("1001")
    @RequestMapping("/bar3")
    public String getBar3(Long batchId, Model model) {
        String center = request.getParameter("center");
        if (center.length() < 0 || center == "") {
            center = getId1();
        }
        EntityWrapper<NetworkSupply> wrapper = new EntityWrapper<NetworkSupply>();
        wrapper.eq("branch_id", center);
        wrapper.groupBy("primary_sales");
        wrapper.setSqlSelect("primary_sales primarys,sum(order_quantity) quantity,count(order_quantity) counts");
        wrapper.eq("batch_id", getProjectId());
        List<Map<String, Object>> mapList = networkSupplyService.selectMaps(wrapper);
        if(mapList.size()==0){
            String message="查询数据异常";
            return callbackFail(message);
        }
        JSONArray dataAxis = new JSONArray();
        JSONArray data = new JSONArray();
        JSONObject ret = new JSONObject();
        JSONArray data2 = new JSONArray();
        for (int i = 0; i < mapList.size(); i++) {
            dataAxis.add(mapList.get(i).get("primarys"));
            data.add(mapList.get(i).get("quantity"));
            data2.add(mapList.get(i).get("counts"));
        }
        ret.put("dataAxis", dataAxis);
        ret.put("y", data);
        ret.put("y2", data2);
        return callbackSuccess(ret);
    }

    @ResponseBody
    @Permission("1001")
    @RequestMapping("/bar4")
    public String getBar4(Long batchId, Model model) {
        String center = request.getParameter("center");
        if (center.length() < 0 || center == "") {
            center = getId1();
        }
        EntityWrapper<NetworkSupply> wrapper = new EntityWrapper<NetworkSupply>();
        wrapper.eq("branch_id", center);
        wrapper.groupBy("delivery_center");
        wrapper.setSqlSelect("delivery_center center,sum(order_quantity) quantity,count(order_quantity) counts");
        wrapper.eq("batch_id", getProjectId());
        List<Map<String, Object>> mapList = networkSupplyService.selectMaps(wrapper);
        if(mapList.size()==0){
            String message="查询数据异常";
            return callbackFail(message);
        }
        JSONArray dataAxis = new JSONArray();
        JSONArray data = new JSONArray();
        JSONArray data2 = new JSONArray();
        JSONObject a1 = null;
        JSONObject ret = new JSONObject();
        for (int i = 0; i < mapList.size(); i++) {
            a1 = new JSONObject();
            a1.put("name", mapList.get(i).get("center"));
            a1.put("value", mapList.get(i).get("quantity"));
            dataAxis.add(mapList.get(i).get("center"));
            data2.add(mapList.get(i).get("counts"));
            data.add(a1);
        }
        ret.put("x", data);
        ret.put("x1", dataAxis);
        ret.put("x2", data2);
        return callbackSuccess(ret);
    }


    @ResponseBody
    @Permission("1001")
    @RequestMapping("/bar5")
    public String getBar5(Long batchId, Model model) {
        Map<String, Object> pm = getParameterMap();
        pm.put("batchId", getProjectId());
        if (pm.get("center").toString().length() < 0 || pm.get("center").toString() == "") {
            pm.put("center", getId1());
        }
        pm.put("operatorId", getCurrentUserId());
        List<Map<String, Object>> mapList = networkSupplyDao.selectOrderTypeQuantityByMonth(pm);
        if(mapList.size()==0){
            String message="查询数据异常";
            return callbackFail(message);
        }
        JSONArray dataAxis = new JSONArray();
        JSONArray data = new JSONArray();
        JSONArray a1 = new JSONArray();
        JSONArray a2 = new JSONArray();
        JSONArray a3 = new JSONArray();
        JSONObject ret = new JSONObject();
        for (int i = 0; i < mapList.size(); i++) {
            a1.add(mapList.get(i).get("quantity"));
            a2.add(mapList.get(i).get("count"));
            a3.add(mapList.get(i).get("months"));
        }
        ret.put("y1", a1);
        ret.put("y2", a2);
        ret.put("x", a3);
        return callbackSuccess(ret);
    }

    //基于百度地图查询来展示订单分析的第一个小页面
    public String getMap2(Long batchId, Model model) {
        JSONArray data = new JSONArray();
        Random random = new Random(47);
        String center = request.getParameter("center");
        if (center.length() < 0 || center == "") {
            center = "广州工贸";
        }
        EntityWrapper<NetworkSupply> wrapper = new EntityWrapper<NetworkSupply>();
        wrapper.eq("branch_center", center);
        wrapper.groupBy("delivery_center");
        wrapper.setSqlSelect("branch_center center,delivery_center last");
        wrapper.eq("batch_id", getProjectId());
        List<Map<String, Object>> mapList = networkSupplyService.selectMaps(wrapper);
        String startnode = center.replace("工贸", "");
        String url = String.format("http://api.map.baidu.com/geocoder?address=%s&output=json&key=%s", URLEncoder.encode(startnode.toString()), "NURx5GUAQ1IBZVBMCQSpYppRsDdTpbxG");
        CloseableHttpClient client = HttpClients.createDefault();
        double lng1 = 0;
        double lat1 = 0;
        try {
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = client.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = httpResponse.getEntity();
                String text = EntityUtils.toString(httpEntity);//取出应答字符串
                JSONObject json = JSONObject.parseObject(text);
                lat1 = json.getJSONObject("result").getJSONObject("location").getDouble("lng");
                lng1 = json.getJSONObject("result").getJSONObject("location").getDouble("lat");


            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        JSONArray nodes = new JSONArray();
        JSONArray res = new JSONArray();
        JSONObject serie = new JSONObject();
        for (int i = 0; i < mapList.size(); i++) {
            String last = mapList.get(i).get("last").toString();
            String url1 = String.format("http://api.map.baidu.com/geocoder?address=%s&output=json&key=%s", URLEncoder.encode(last), "NURx5GUAQ1IBZVBMCQSpYppRsDdTpbxG");
            CloseableHttpClient client1 = HttpClients.createDefault();
            try {
                HttpGet httpGet1 = new HttpGet(url1);
                HttpResponse httpResponse = client.execute(httpGet1);
                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                    HttpEntity httpEntity1 = httpResponse.getEntity();
                    String text = EntityUtils.toString(httpEntity1);//取出应答字符串
                    JSONObject json1 = JSONObject.parseObject(text);
                    double lat2 = json1.getJSONObject("result").getJSONObject("location").getDouble("lng");
                    double lng2 = json1.getJSONObject("result").getJSONObject("location").getDouble("lat");
                    nodes.add(new NodeData("", Arrays.asList(lat2, lng2, random.nextInt(100))));
                    serie.put("name", center.replace("工贸", ""));
                    JSONObject res1 = new JSONObject();
                    res1.put("fromName", center.replace("工贸", ""));
                    res1.put("toName", last);
                    JSONArray fromCoord = new JSONArray();
                    fromCoord.add(lat1);
                    fromCoord.add(lng1);
                    JSONArray toCoord = new JSONArray();
                    toCoord.add(lat2);
                    toCoord.add(lng2);
                    JSONArray coords = new JSONArray();
                    coords.add(fromCoord);
                    coords.add(toCoord);
                    res1.put("coords", coords);
                    res.add(res1);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        serie.put("res", res);
        serie.put("nodes", nodes);
        data.add(serie);
        return callbackSuccess(data);
    }

    @ResponseBody
    @Permission("1001")
    @RequestMapping("/bar6")
    public String getBar6(Long batchId, Model model) {
        Map<String, Object> pm = getParameterMap();
        pm.put("batchId", getProjectId());
        if (pm.get("center").toString().length() < 0 || pm.get("center").toString() == "") {
            pm.put("center", getId1());
        }
        pm.put("operatorId", getCurrentUserId());
        List<Map<String, Object>> mapList = networkSupplyDao.selectOrderByType(pm);
        if(mapList.get(0).containsKey("months")==false){
            String message="查询数据异常";
            return callbackFail(message);
        }
        JSONArray a1 = new JSONArray();
        JSONArray a2 = new JSONArray();
        JSONArray a3 = new JSONArray();
        JSONObject ret = new JSONObject();
        for (int i = 0; i < mapList.size(); i++) {
            a1.add(mapList.get(i).get("months").toString() + mapList.get(i).get("order_type").toString());
            a2.add(mapList.get(i).get("quantity"));
            a3.add(mapList.get(i).get("counts"));
        }
        ret.put("data1", a1);
        ret.put("data2", a2);
        ret.put("data3", a3);
        return callbackSuccess(ret);
    }

    /**
     * 登录
     */
    @RequestMapping("/bar11")
    @Permission("1001")
    public String bar11(Long batchId, Model model) {
        model.addAttribute("batchId", batchId);
        return "/lpp/network/supply/bar1";
    }


}
